package com.myspring.dao.impl;

import com.myspring.dao.ProductDao;
import com.myspring.mapper.ProductMapper;
import com.myspring.po.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * ClassName: ProductDaoImpl
 * Package: com.mystring.dao.impl
 * Description:
 *
 * @Author 刘英杰
 * @Create 2024/12/6 21:08
 * @Version 1.0
 */

@Repository
public class ProductDaoImpl implements ProductDao {
    /*交给Spring注入*/
/*    @Autowired
//    @Resource(name = "queryRunner")
//    @Resource
    private QueryRunner queryRunner;*/

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    ProductMapper productMapper;

    @Override
    public void saveProduct(Product product) {
        jdbcTemplate.update("INSERT INTO spring.product(pname,price,category) VALUES (?,?,?)",
                product.getPname(),product.getPrice(),product.getCategory());
    }

    @Override
    public void deleteProduct(int id) {
        jdbcTemplate.update("DELETE FROM spring.product WHERE pid=?",id);
    }


    @Override
    public void updateProduct(Product product) {
        jdbcTemplate.update("UPDATE spring.product SET pname = ?,price = ?,category = ? WHERE pid = ?",
                product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
//        int a =  1/0;
    }



    @Override
    public Product findById(int id) {
        /**
         * queryForObject:
         *      第一个参数:sql语句
         *      第二个参数:结果集类型
         *      第三个参数:?占位符对应的值
         */
        return jdbcTemplate.queryForObject("SELECT * FROM spring.product WHERE pid=?",productMapper,id);
    }


    @Override
    public List<Product> findAll() {
        return jdbcTemplate.query("SELECT * FROM spring.product",productMapper) ;
    }
}
